package com.vnp.vchat.version2;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;

import net.appkraft.parallax.ParallaxScrollView;

import org.json.JSONObject;

import android.app.Activity;
import android.app.Dialog;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Build.VERSION_CODES;
import android.os.Bundle;
import android.provider.MediaStore;
import android.provider.MediaStore.MediaColumns;
import android.util.Base64;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.RequestParams;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.vnp.vchat.R;
import com.vnp.vchat.httpclient.MyJsonHttpResponseHandler;
import com.vnp.vchat.util.Common;
import com.vnp.vchat.util.DecodeUtils;
import com.vnp.vchat.util.KeyboardHelper;
import com.vnp.vchat.util.PreferenceHelper;
import com.vnp.vchat.util.Utils;

public class ThongtincanhanActivity extends Activity implements OnClickListener{

	
	ParallaxScrollView parallax;
	ImageView image;
	
	EditText edtTen, edtEmail, edtSodt;
	
	RelativeLayout main;
	
	ImageButton btnBack;
	TextView title;
	
	ImageButton btnChangeImage;
	// show dialog chon anh
	Dialog dChoose;
	
	String TEMP_TAKE_IMAGE = Common.SDCARD_IMAGE + "tmp_avatar_setup.jpg";
	String file_path;
	
	// chon anh
	private static final int PICK_PHOTO = 100;
	private static final int CAPTURE_PHOTO = 200;
	
	Uri mCapturedImageURI;
	String selectedPath;
	Uri selectedImageUri;
	
	byte[] byteArray;
	
	PreferenceHelper preferenceHelper;
	
	Button btnCapnhat;
	
	DisplayImageOptions options = new DisplayImageOptions.Builder()
								.cacheInMemory(false).cacheOnDisc(true)
								.bitmapConfig(Config.RGB_565)
								.showImageForEmptyUri(R.drawable.no_avatar)
								.showImageOnLoading(R.drawable.no_avatar)
								.build();
	
	ProgressBar progressBar;
	
	
	@Override
	protected void onResume() {
		super.onResume();
		Common.appRunning = true;
	}
	@Override
	protected void onPause() {
		super.onPause();
		Common.appRunning = false;
	}
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_thongtincanhan);
		
		main = (RelativeLayout) findViewById(R.id.main);
		
		preferenceHelper = new PreferenceHelper(this);
		
		KeyboardHelper.setupUI(ThongtincanhanActivity.this, main);
		
		
		btnBack = (ImageButton) findViewById(R.id.btn_function1);
		
		btnBack.setVisibility(View.VISIBLE);
		
		btnChangeImage = (ImageButton) findViewById(R.id.btn_capture);
		
		title = (TextView) findViewById(R.id.title);
		parallax = (ParallaxScrollView) findViewById(R.id.scrollView1);
		image = (ImageView) findViewById(R.id.imageView1);
		parallax.setImageViewToParallax(image);
//		image.setImageResource(R.drawable.no_avatar);
		
		edtTen = (EditText) findViewById(R.id.txt_ten);
		edtEmail = (EditText) findViewById(R.id.txt_email);
		edtSodt = (EditText) findViewById(R.id.txt_sodt);
		
		btnCapnhat = (Button) findViewById(R.id.btn_cap_nhat);
		progressBar = (ProgressBar) findViewById(R.id.progressBar1);
		
		init();
		
		setFont();
		
		setValue();
		
	}
	
	void setValue(){
		edtTen.setText(preferenceHelper.getUserName());
		edtEmail.setText(preferenceHelper.getEmail());
		if(preferenceHelper.getPhone().equals("")){
			
		}else {
			edtSodt.setText(preferenceHelper.getPhone());
		}
		
		Log.i("DATA", "Link avatar: "+preferenceHelper.getMyAvatar());
		
		ImageLoader.getInstance().displayImage(preferenceHelper.getMyAvatar(), image, options);
	}
	
	void init(){
		title.setText("Thông tin cá nhân");
		btnBack.setOnClickListener(this);
		btnChangeImage.setOnClickListener(this);
		btnCapnhat.setOnClickListener(this);
		
	}
	
	void setFont(){
		title.setTypeface(Utils.getTypefaceBold(ThongtincanhanActivity.this));
		edtTen.setTypeface(Utils.getTypefaceRegular(ThongtincanhanActivity.this));
		edtEmail.setTypeface(Utils.getTypefaceRegular(ThongtincanhanActivity.this));
		edtSodt.setTypeface(Utils.getTypefaceRegular(ThongtincanhanActivity.this));
	}
	
	@Override
	public void onBackPressed() {
		closeActivity();
	}
	
	void closeActivity(){
		finish();
		overridePendingTransition(R.anim.over_main_right, R.anim.trans_right_out);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_function1:
			closeActivity();
			break;
		case R.id.btn_capture:
			showDialogChonanh();
			break;
		case R.id.btn_choose_image:
			dChoose.dismiss();
			openGallery();
			break;
		case R.id.btn_capture_image:
			dChoose.dismiss();
			takeImage();
			break;
		case R.id.btn_thoat:
			dChoose.dismiss();
			break;
		case R.id.btn_cap_nhat:
			uploadImage();
			break;
		default:
			break;
		}
	}
	
	// show dialog sau khi them thanh cong
		public void showDialogChonanh() {
			dChoose = new Dialog(this, R.style.DialogSlideAnim);
			dChoose.requestWindowFeature(Window.FEATURE_NO_TITLE);
			dChoose.setContentView(R.layout.dialog_choose_photo);

			Button btnChonanh = (Button) dChoose
					.findViewById(R.id.btn_choose_image);
			Button btnChupanh = (Button) dChoose
					.findViewById(R.id.btn_capture_image);

			Button btnThoat = (Button) dChoose.findViewById(R.id.btn_thoat);
			
			btnChonanh.setTypeface(Utils.getTypefaceRegular(ThongtincanhanActivity.this));
			btnChupanh.setTypeface(Utils.getTypefaceRegular(ThongtincanhanActivity.this));
//					btnThoat.setTypeface(Utils.getTypefaceBold(ChatActivity.this), Typeface.BOLD);
			
			dChoose.show();
			dChoose.getWindow().setBackgroundDrawable(new ColorDrawable(0));
			dChoose.setCanceledOnTouchOutside(true);
			dChoose.getWindow().setGravity(Gravity.BOTTOM);
			dChoose.show();

			// setonclick
			btnChonanh.setOnClickListener(this);
			btnChupanh.setOnClickListener(this);
			btnThoat.setOnClickListener(this);
		}
				
		// chon anh
		public void openGallery() {
			File ff = new File(TEMP_TAKE_IMAGE);
			if (ff.exists())
				ff.delete();
			Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
			photoPickerIntent.setType("image/*");
			startActivityForResult(photoPickerIntent, PICK_PHOTO);
		}
		
		// chup anh
		public void takeImage() {
			String fileName = "temp.jpg";
			ContentValues values = new ContentValues();
			values.put(MediaColumns.TITLE, fileName);
			mCapturedImageURI = getContentResolver().insert(
					MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);

			Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
			intent.putExtra(MediaStore.EXTRA_OUTPUT, mCapturedImageURI);
			startActivityForResult(intent, CAPTURE_PHOTO);
		}
		
		@Override
		protected void onActivityResult(int requestCode, int resultCode,
				Intent data) {
			super.onActivityResult(requestCode, resultCode, data);
			if (resultCode == RESULT_OK) {
				switch (requestCode) {
				case PICK_PHOTO:
					Uri u = data.getData();
					String[] filePathColumn = { MediaColumns.DATA };
					Cursor cursor = getContentResolver().query(u, filePathColumn,
							null, null, null);
					cursor.moveToFirst();
					int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
					file_path = cursor.getString(columnIndex);

					Log.i("DATA", "File upload :" + file_path);
					
					
					
					Bitmap bm = DecodeUtils.decode(ThongtincanhanActivity.this,
							Uri.parse(file_path), 800, 800);
					
					Log.i("vChat", "Width: "+bm.getWidth() + "Height: "+bm.getHeight());
					
					if (bm == null) {
						Toast.makeText(ThongtincanhanActivity.this,
								"Bạn chưa chọn ảnh!", Toast.LENGTH_SHORT).show();
						return;
					}
					
					ByteArrayOutputStream stream = new ByteArrayOutputStream();
					bm.compress(Bitmap.CompressFormat.JPEG, 75, stream);
					byteArray = stream.toByteArray();

					image.setImageBitmap(bm);
					
					// upload image
//					uploadImage();
					try {
						if (cursor != null){
							cursor.close();	
						}
					} catch (IllegalStateException e) {
						e.printStackTrace();
					}

					break;
				case CAPTURE_PHOTO:
					String[] projection = { MediaColumns.DATA };
					Cursor cursor1 = managedQuery(mCapturedImageURI, projection,
							null, null, null);
					int column_index_data = cursor1
							.getColumnIndexOrThrow(MediaColumns.DATA);
					cursor1.moveToFirst();
					file_path = cursor1.getString(column_index_data);
					Log.i("DATA", "File upload :" + file_path);

					Bitmap bm1 = DecodeUtils.decode(ThongtincanhanActivity.this,
							Uri.parse(file_path), 800, 800);
					if (bm1 == null) {
						Toast.makeText(ThongtincanhanActivity.this,
								"Bạn chưa chọn ảnh!", Toast.LENGTH_SHORT).show();
						return;
					}
					
					ByteArrayOutputStream stream1 = new ByteArrayOutputStream();
					bm1.compress(Bitmap.CompressFormat.JPEG, 75, stream1);
					byteArray = stream1.toByteArray();
					
					image.setImageBitmap(bm1);
					
//					imgTungbuoc.setScaleType(ScaleType.CENTER_CROP);
//					imgTungbuoc.setImageBitmap(bm1);

//					uploadImage();
					try {
						if (cursor1 != null){
							cursor1.close();
						} 
					} catch (IllegalStateException e) {
						e.printStackTrace();
					}
					break;
				}
			}
		}
		
		
		@Override
		@Deprecated
		public void startManagingCursor(Cursor c) {
			if (Build.VERSION.SDK_INT < VERSION_CODES.HONEYCOMB) {
		        super.startManagingCursor(c);
		    }
		}
		
		void uploadImage() {
			progressBar.setVisibility(View.VISIBLE);
			btnCapnhat.setText("Đang cập nhật...");
			
			try {
				RequestParams params = new RequestParams();
				params.put("acc_id", preferenceHelper.getUserId());
				params.put("full_name", edtTen.getText().toString());
				
				if (!byteArray.equals(null)){
					params.put("avatar", new ByteArrayInputStream(byteArray), "image.jpg");
				}

				AsyncHttpClient client = new AsyncHttpClient();
				try {
					String credentials = "vchat-mobile" + ":" + "I2o5VG0c5a5dnZ866Y8Sguthojavuw";  
					String base64EncodedCredentials = Base64.encodeToString(credentials.getBytes(), Base64.NO_WRAP); 
					client.addHeader("Authorization", "Basic " + base64EncodedCredentials);
					
				} catch (Exception e) {
					e.printStackTrace();
				}
				client.post("https://id.vatgia.com/api/v1/accountSetting/updateInfo", params,
						new MyJsonHttpResponseHandler() {

							@Override
							public void onSuccess(int statusCode, JSONObject re) {
								
								progressBar.setVisibility(View.GONE);
								btnCapnhat.setText("Cập nhật");
								
								Log.i("DATA", "STATUS CODE: "+statusCode + "DATA: "+re.toString());
								Toast.makeText(ThongtincanhanActivity.this, "Cập nhật thành công.", Toast.LENGTH_SHORT).show();
							}

							@Override
							public void onFailure(int statusCode, Throwable error) {
								progressBar.setVisibility(View.GONE);
								btnCapnhat.setText("Cập nhật");
								Log.i("DATA", "STATUS CODE: "+statusCode+"ERROR: "+error.toString());
								Toast.makeText(ThongtincanhanActivity.this, "Cập nhật thất bại.", Toast.LENGTH_SHORT).show();
							}
						});
			} catch (Exception e) {
				
			}
			
		}
	
	
}
